package api

import (
	"gateway/basic/config"
	order "gateway/basic/proto/orderproto"
	"gateway/handler/request"
	"gateway/handler/response"
	"gateway/websocket"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// CreateOrder
// @Summary      创建订单
// @Description  创建订单
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.CreateOrderFlatRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/createOrder [post]
func CreateOrder(c *gin.Context) {
	var req request.CreateOrderFlatRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 类型转换
	orderType, err := strconv.ParseInt(req.OrderType, 10, 32)
	if err != nil {
		response.ParameterError(c, "订单类型格式错误", nil)
		return
	}

	itemType, err := strconv.ParseInt(req.ItemType, 10, 32)
	if err != nil {
		response.ParameterError(c, "商品类型格式错误", nil)
		return
	}

	unitPrice, err := strconv.ParseFloat(req.UnitPrice, 64)
	if err != nil {
		response.ParameterError(c, "单价格式错误", nil)
		return
	}

	quantity, err := strconv.ParseFloat(req.Quantity, 64)
	if err != nil {
		response.ParameterError(c, "数量格式错误", nil)
		return
	}

	billingCycle, err := strconv.ParseInt(req.BillingCycle, 10, 32)
	if err != nil {
		response.ParameterError(c, "计费周期格式错误", nil)
		return
	}

	// 创建订单明细
	orderItem := &order.OrderItem{
		ItemType:         int32(itemType),
		ItemName:         req.ItemName,
		ItemDesc:         req.ItemDesc,
		UnitPrice:        unitPrice,
		Quantity:         quantity,
		BillingCycle:     int32(billingCycle),
		BillingStartDate: req.BillingStartDate,
		BillingEndDate:   req.BillingEndDate,
	}

	createOrder, err := config.OrderClient.CreateOrder(c.Request.Context(), &order.CreateOrderReq{
		OrderType:      int32(orderType),
		TenantId:       req.TenantID,
		LandlordId:     req.LandlordID,
		PropertyId:     req.PropertyID,
		AgentId:        req.AgentID,
		LeaseStartDate: req.LeaseStartDate,
		LeaseEndDate:   req.LeaseEndDate,
		Items:          []*order.OrderItem{orderItem},
		Remark:         req.Remark,
	})
	if err != nil {
		response.SrvError(c, "创建订单失败: "+err.Error(), nil)
		return
	}

	// 发送WebSocket通知
	if createOrder.Code == 200 {
		// 获取订单详情用于通知
		orderDetail, err := config.OrderClient.GetOrder(c.Request.Context(), &order.GetOrderReq{
			OrderId: createOrder.OrderId,
		})
		if err == nil && orderDetail.Code == 200 {
			websocket.NotifyOrderCreatedGlobal(orderDetail.Order)
		}
	}

	response.Success(c, "创建订单成功", createOrder)
}

// GetOrder
// @Summary      获取订单详情
// @Description  获取订单详情
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  query      request.GetOrder  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/getOrder [get]
func GetOrder(c *gin.Context) {
	var req request.GetOrder
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}
	getOrder, err := config.OrderClient.GetOrder(c.Request.Context(), &order.GetOrderReq{
		OrderId: req.OrderID,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "订单不存在",
			Data: nil,
		})
	}
	response.Success(c, "获取订单详情成功", getOrder)
}

// GetOrdersByTenant
// @Summary      获取租客订单列表
// @Description  获取租客订单列表
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  query      request.GetOrdersByTenantRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/getOrdersByTenant [get]
func GetOrdersByTenant(c *gin.Context) {
	var req request.GetOrdersByTenantRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	getOrders, err := config.OrderClient.GetOrdersByTenant(c.Request.Context(), &order.GetOrdersByTenantReq{
		TenantId: req.TenantID,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "获取订单列表失败",
		})
		return
	}
	response.Success(c, "获取租客订单列表成功", getOrders)
}

// GetOrdersByLandlord
// @Summary      获取房东订单列表
// @Description  获取房东订单列表
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  query      request.GetOrdersByLandlordRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/getOrdersByLandlord [get]
func GetOrdersByLandlord(c *gin.Context) {
	var req request.GetOrdersByLandlordRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	getOrders, err := config.OrderClient.GetOrdersByLandlord(c.Request.Context(), &order.GetOrdersByLandlordReq{
		LandlordId: req.LandlordID,
		Page:       req.Page,
		PageSize:   req.PageSize,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "获取订单列表失败",
		})
		return
	}
	response.Success(c, "获取房东订单列表成功", getOrders)
}

// UpdateOrderStatus
// @Summary      更新订单状态
// @Description  更新订单状态
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.UpdateOrderStatusRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/updateOrderStatus [post]
func UpdateOrderStatus(c *gin.Context) {
	var req request.UpdateOrderStatusRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	// 先获取当前订单状态
	currentOrder, err := config.OrderClient.GetOrder(c.Request.Context(), &order.GetOrderReq{
		OrderId: req.OrderID,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "获取订单信息失败",
		})
		return
	}

	oldStatus := currentOrder.Order.OrderStatus

	updateStatus, err := config.OrderClient.UpdateOrderStatus(c.Request.Context(), &order.UpdateOrderStatusReq{
		OrderId:      req.OrderID,
		Status:       req.Status,
		OperatorId:   req.OperatorID,
		OperatorType: req.OperatorType,
		Reason:       req.Reason,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "更新订单状态失败",
		})
		return
	}

	// 发送WebSocket通知
	if updateStatus.Code == 200 {
		// 获取更新后的订单详情
		updatedOrder, err := config.OrderClient.GetOrder(c.Request.Context(), &order.GetOrderReq{
			OrderId: req.OrderID,
		})
		if err == nil && updatedOrder.Code == 200 {
			websocket.NotifyOrderStatusChangeGlobal(updatedOrder.Order, oldStatus)
		}
	}

	response.Success(c, "订单状态更新成功", updateStatus)
}

// CreatePayment
// @Summary      创建支付记录
// @Description  创建支付记录
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.CreatePaymentRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/createPayment [post]
func CreatePayment(c *gin.Context) {
	var req request.CreatePaymentRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	createPayment, err := config.OrderClient.CreatePayment(c.Request.Context(), &order.CreatePaymentReq{
		OrderId:        req.OrderID,
		PaymentType:    req.PaymentType,
		PaymentMethod:  req.PaymentMethod,
		PaymentChannel: req.PaymentChannel,
		Amount:         req.Amount,
		Remark:         req.Remark,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "创建支付记录失败",
		})
		return
	}
	response.Success(c, "支付记录创建成功", createPayment)
}

// ProcessPayment
// @Summary      处理支付
// @Description  处理支付
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.ProcessPaymentRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/processPayment [post]
func ProcessPayment(c *gin.Context) {
	var req request.ProcessPaymentRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	processPayment, err := config.OrderClient.ProcessPayment(c.Request.Context(), &order.ProcessPaymentReq{
		PaymentId:     req.PaymentID,
		TransactionId: req.TransactionID,
		Status:        req.Status,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "处理支付失败",
		})
		return
	}

	// 发送WebSocket通知
	if processPayment.Code == 200 {
		// 获取订单详情用于通知
		orderDetail, err := config.OrderClient.GetOrder(c.Request.Context(), &order.GetOrderReq{
			OrderId: req.OrderID,
		})
		if err == nil && orderDetail.Code == 200 {
			websocket.NotifyPaymentUpdateGlobal(orderDetail.Order)
		}
	}

	response.Success(c, "支付处理成功", processPayment)
}

// CreateContract
// @Summary      创建合同
// @Description  创建合同
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.CreateContractRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/createContract [post]
func CreateContract(c *gin.Context) {
	var req request.CreateContractRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误",
			Data: err.Error(),
		})
		return
	}

	createContract, err := config.OrderClient.CreateContract(c.Request.Context(), &order.CreateContractReq{
		OrderId:         req.OrderID,
		ContractType:    req.ContractType,
		ContractContent: req.ContractContent,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "创建合同失败",
		})
		return
	}
	response.Success(c, "合同创建成功", createContract)
}

// SignContract
// @Summary      签署合同
// @Description  签署合同
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.SignContractRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/signContract [post]
func SignContract(c *gin.Context) {
	var req request.SignContractRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	signContract, err := config.OrderClient.SignContract(c.Request.Context(), &order.SignContractReq{
		ContractId: req.ContractID,
		SignerId:   req.SignerID,
		Signature:  req.Signature,
		SignerType: req.SignerType,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "签署合同失败",
		})
		return
	}
	response.Success(c, "合同签署成功", signContract)
}

// CreateReview
// @Summary      创建评价
// @Description  创建评价
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.CreateReviewRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/createReview [post]
func CreateReview(c *gin.Context) {
	var req request.CreateReviewRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	createReview, err := config.OrderClient.CreateReview(c.Request.Context(), &order.CreateReviewReq{
		OrderId:             req.OrderID,
		ReviewerId:          req.ReviewerID,
		RevieweeId:          req.RevieweeID,
		ReviewType:          req.ReviewType,
		OverallRating:       req.OverallRating,
		ServiceRating:       req.ServiceRating,
		CommunicationRating: req.CommunicationRating,
		CleanlinessRating:   req.CleanlinessRating,
		ValueRating:         req.ValueRating,
		Content:             req.Content,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "创建评价失败",
		})
		return
	}
	response.Success(c, "评价创建成功", createReview)
}

// CreateComplaint
// @Summary      创建投诉
// @Description  创建投诉
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.CreateComplaintRequest  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/createComplaint [post]
func CreateComplaint(c *gin.Context) {
	var req request.CreateComplaintRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	createComplaint, err := config.OrderClient.CreateComplaint(c.Request.Context(), &order.CreateComplaintReq{
		OrderId:       req.OrderID,
		ComplainantId: req.ComplainantID,
		RespondentId:  req.RespondentID,
		ComplaintType: req.ComplaintType,
		Title:         req.Title,
		Content:       req.Content,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "创建投诉失败",
		})
		return
	}
	response.Success(c, "投诉创建成功", createComplaint)
}

// DeleteOrder
// @Summary      删除订单
// @Description  删除订单
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.DeleteOrder  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/deleteOrder [post]
func DeleteOrder(c *gin.Context) {
	var req request.DeleteOrder
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	deleteOrder, err := config.OrderClient.DeleteOrder(c.Request.Context(), &order.DeleteOrderReq{
		OrderId: uint64(req.OrderId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "删除订单失败",
		})
		return
	}
	response.Success(c, "订单删除成功", deleteOrder)
}

// GetOrderStatistics
// @Summary      获取订单统计
// @Description  获取订单统计
// @Tags         订单模块
// @Accept       json
// @Produce      json
// @Param        user  query      request.GetOrderStatistics  true  "订单参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /order/getOrderStatistics [get]
func GetOrderStatistics(c *gin.Context) {
	var req request.GetOrderStatistics
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	getStatistics, err := config.OrderClient.GetOrderStatistics(c.Request.Context(), &order.GetOrderStatisticsReq{
		TenantId:   req.TenantID,
		LandlordId: req.LandlordID,
		StartDate:  req.StartDate,
		EndDate:    req.EndDate,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, response.Response{
			Code: 500,
			Msg:  "获取统计信息失败",
		})
		return
	}
	response.Success(c, "获取统计信息成功", getStatistics)
}

// AcceptOrder 接单操作
// @Summary 接单操作
// @Description 操作员接单处理
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param request body request.AcceptOrderRequest true "接单请求"
// @Success 200 {object} response.Response "接单成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/accept [post]
func AcceptOrder(c *gin.Context) {
	var req request.AcceptOrderRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.AcceptOrderReq{
		OrderId:      req.OrderID,
		OperatorId:   string(req.OperatorID),
		OperatorType: string(req.OperatorType),
		Reason:       req.Reason,
	}

	rpcResp, err := config.OrderClient.AcceptOrder(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "接单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	// 发送WebSocket通知
	websocket.NotifyOrderStatusChangeGlobal(&order.OrderInfo{
		Id:          rpcResp.OrderId,
		OrderNo:     rpcResp.OrderNo,
		OrderStatus: 1, // 已确认状态
	}, 0) // 从待确认状态变更

	response.Success(c, "接单成功", map[string]interface{}{
		"order_id":    rpcResp.OrderId,
		"order_no":    rpcResp.OrderNo,
		"accepted_at": rpcResp.AcceptedAt,
	})
}

// RejectOrder 拒绝订单
// @Summary 拒绝订单
// @Description 操作员拒绝订单
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param request body request.RejectOrderRequest true "拒绝订单请求"
// @Success 200 {object} response.Response "拒绝成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/reject [post]
func RejectOrder(c *gin.Context) {
	var req request.RejectOrderRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.RejectOrderReq{
		OrderId:      req.OrderID,
		OperatorId:   req.OperatorID,
		OperatorType: req.OperatorType,
		Reason:       req.Reason,
	}

	rpcResp, err := config.OrderClient.RejectOrder(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "拒绝订单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	// 发送WebSocket通知
	websocket.NotifyOrderStatusChangeGlobal(&order.OrderInfo{
		Id:          rpcResp.OrderId,
		OrderNo:     rpcResp.OrderNo,
		OrderStatus: 4, // 已取消状态
	}, 0) // 从待确认状态变更

	response.Success(c, "拒绝订单成功", map[string]interface{}{
		"order_id":    rpcResp.OrderId,
		"order_no":    rpcResp.OrderNo,
		"rejected_at": rpcResp.RejectedAt,
	})
}

// GetPendingOrders 获取待处理订单列表
// @Summary 获取待处理订单列表
// @Description 获取待接单的订单列表
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(10)
// @Param status query int false "订单状态" default(1)
// @Success 200 {object} response.Response "获取成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/pending [get]
func GetPendingOrders(c *gin.Context) {
	var req request.GetPendingOrdersRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.GetPendingOrdersReq{
		Page:       req.Page,
		PageSize:   req.PageSize,
		Status:     req.Status,
		OperatorId: req.OperatorID,
	}

	rpcResp, err := config.OrderClient.GetPendingOrders(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "获取待处理订单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	// 转换订单数据
	var orders []map[string]interface{}
	for _, orderInfo := range rpcResp.Orders {
		order := map[string]interface{}{
			"order_id":         orderInfo.Id,
			"order_no":         orderInfo.OrderNo,
			"order_status":     orderInfo.OrderStatus,
			"payment_status":   orderInfo.PaymentStatus,
			"total_amount":     orderInfo.TotalAmount,
			"paid_amount":      orderInfo.PaidAmount,
			"tenant_id":        orderInfo.TenantId,
			"landlord_id":      orderInfo.LandlordId,
			"property_id":      orderInfo.PropertyId,
			"agent_id":         orderInfo.AgentId,
			"lease_start_date": orderInfo.LeaseStartDate,
			"lease_end_date":   orderInfo.LeaseEndDate,
			"contract_status":  orderInfo.ContractStatus,
			"contract_url":     orderInfo.ContractUrl,
			"remark":           orderInfo.Remark,
			"created_at":       orderInfo.CreatedAt,
			"updated_at":       orderInfo.UpdatedAt,
		}
		orders = append(orders, order)
	}

	response.Success(c, "获取待处理订单成功", map[string]interface{}{
		"orders":    orders,
		"total":     rpcResp.Total,
		"page":      rpcResp.Page,
		"page_size": rpcResp.PageSize,
	})
}

// AssignOrder 分配订单
// @Summary 分配订单
// @Description 将订单分配给指定操作员
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param request body request.AssignOrderRequest true "分配订单请求"
// @Success 200 {object} response.Response "分配成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/assign [post]
func AssignOrder(c *gin.Context) {
	var req request.AssignOrderRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误："+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.AssignOrderReq{
		OrderId:        req.OrderID,
		AssignedTo:     req.AssignedTo,
		AssignedBy:     req.AssignedBy,
		AssignmentNote: req.AssignmentNote,
	}

	rpcResp, err := config.OrderClient.AssignOrder(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "分配订单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	// 发送WebSocket通知给被分配的操作员
	websocket.NotifyOrderAssigned(req.AssignedTo, req.OrderID)

	response.Success(c, "订单分配成功", map[string]interface{}{
		"order_id":    rpcResp.OrderId,
		"assigned_to": rpcResp.AssignedTo,
		"assigned_at": rpcResp.AssignedAt,
	})
}

// GetOrderAcceptanceStats 获取接单统计
// @Summary 获取接单统计
// @Description 获取接单相关的统计数据
// @Tags 统计分析
// @Accept json
// @Produce json
// @Param operator_id query string false "操作员ID"
// @Param start_date query string false "开始日期"
// @Param end_date query string false "结束日期"
// @Success 200 {object} response.Response "获取成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/acceptance-stats [get]
func GetOrderAcceptanceStats(c *gin.Context) {
	var req request.GetOrderAcceptanceStatsRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 暂时使用模拟统计数据
	mockStats := map[string]interface{}{
		"total_orders":        100,
		"accepted_orders":     80,
		"rejected_orders":     10,
		"pending_orders":      10,
		"acceptance_rate":     0.8,
		"average_accept_time": 300, // 5分钟
		"today_orders":        20,
		"today_accepted":      15,
	}

	response.Success(c, "获取接单统计成功", mockStats)
}

// BatchAcceptOrders 批量接单
// @Summary 批量接单
// @Description 批量接单操作
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param request body request.BatchAcceptOrdersRequest true "批量接单请求"
// @Success 200 {object} response.Response "批量接单成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/batch-accept [post]
func BatchAcceptOrders(c *gin.Context) {
	var req request.BatchAcceptOrdersRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.BatchAcceptOrdersReq{
		OrderIds:     req.OrderIDs,
		OperatorId:   string(req.OperatorID),
		OperatorType: string(req.OperatorType),
		Reason:       req.Reason,
	}

	rpcResp, err := config.OrderClient.BatchAcceptOrders(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "批量接单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	response.Success(c, "批量接单成功", map[string]interface{}{
		"success_count": rpcResp.SuccessCount,
		"failed_count":  rpcResp.FailedCount,
		"failed_orders": rpcResp.FailedOrders,
	})
}

// BatchRejectOrders 批量拒绝订单
// @Summary 批量拒绝订单
// @Description 批量拒绝订单操作
// @Tags 接单管理
// @Accept json
// @Produce json
// @Param request body request.BatchRejectOrdersRequest true "批量拒绝订单请求"
// @Success 200 {object} response.Response "批量拒绝成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/orders/batch-reject [post]
func BatchRejectOrders(c *gin.Context) {
	var req request.BatchRejectOrdersRequest
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "请求参数错误: "+err.Error(), err.Error())
		return
	}

	// 调用RPC服务
	rpcReq := &order.BatchRejectOrdersReq{
		OrderIds:     req.OrderIDs,
		OperatorId:   string(req.OperatorID),
		OperatorType: string(req.OperatorType),
		Reason:       req.Reason,
	}

	rpcResp, err := config.OrderClient.BatchRejectOrders(c.Request.Context(), rpcReq)
	if err != nil {
		response.SrvError(c, "批量拒绝订单失败: "+err.Error(), err.Error())
		return
	}

	if rpcResp.Code != 200 {
		response.SrvError(c, rpcResp.Message, nil)
		return
	}

	response.Success(c, "批量拒绝订单成功", map[string]interface{}{
		"success_count": rpcResp.SuccessCount,
		"failed_count":  rpcResp.FailedCount,
		"failed_orders": rpcResp.FailedOrders,
	})
}
